package com.codejoys.ssm.exception;

import com.codejoys.ssm.dto.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 所有业务异常，使用这个类同统一处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger=LoggerFactory.getLogger(GlobalExceptionHandler.class);
    //捕获到TmsException之后，返回一个json消息，里面有code，message
    @ExceptionHandler(TmsException.class)
    @ResponseBody
    public BaseResult handleException(TmsException e){

        logger.error("捕获到异常",e);
        return new BaseResult(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(AccessDeniedException.class)
    public void handleAccessDenyException(AccessDeniedException e, HttpServletResponse response) {
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        } catch (IOException ex) {
            logger.error("IO出错", ex);
        }
    }


    @ExceptionHandler
    @ResponseBody
    public BaseResult handleOtherException(RuntimeException e) {
        logger.error("未知异常", e);

        return new BaseResult(10000, "服务器内部错误，请稍后重新");
    }
}
